import closeImg from '../../../assets/teaching/closefangdajing.svg';

export const getBase64Image = (imgurl, startX, startY, width = 300, height = 300) =>
  new Promise((resolve) => {
    const img = new Image();
    img.setAttribute('crossOrigin', 'anonymous');
    img.onload = () => {
      const canvasImg = document.createElement('canvas');
      canvasImg.width = width;
      canvasImg.height = height;
      const ctx = canvasImg.getContext('2d');
      ctx.drawImage(img, startX, startY, width, height, 0, 0, width, height);
      const dataURL = canvasImg.toDataURL('image/png', 1.0);
      const link = document.createElement('a');
      link.href = dataURL;
      const now = new Date();
      const data = now.toLocaleDateString();
      let num = '';
      for (let i = 0; i < 3; i++) {
        num += Math.floor(Math.random() * 10);
      }
      link.download = `数字教材截图${data}/${num}.png`;
      link.click();
      resolve(dataURL);
    };
    img.src = imgurl;
  });
export const getImageData = async (image, callback) =>
  new Promise((resolve) => {
    // 找个最外层的容器
    const ele = document.getElementsByTagName('body')[0];
    const ctxData = image;
    const boxDiv = document.createElement('div');
    boxDiv.className = 'boxDiv';
    boxDiv.style.cursor = 'move';
    const boxDivBig = document.createElement('div');
    boxDivBig.className = 'boxDivBig';
    setStyles(boxDivBig, {
      width: '100%',
      height: '100%',
      background: 'rgba(0, 0, 0, 0.65)',
      position: 'absolute',
      zIndex: 105,
      left: '0',
      top: '0',
      userSelect: 'none',
    });

    const bgIimg = document.createElement('img');
    bgIimg.src = image;

    setStyles(bgIimg, {
      width: '100%',
      height: '100%',
      position: 'absolute',
      userSelect: 'none',
      zIndex: 0,
    });

    ele.style.cursor = 'crosshair';
    ele.appendChild(boxDivBig);
    ele.appendChild(bgIimg);

    // x, √  操作部分 top------------------
    const caozuoDiv = document.createElement('div');
    caozuoDiv.setAttribute(
      'style',
      'text-align: center;position: absolute; top: -38px;right: 0px; background: #FC8B09; line-height: 32px;',
    );
    const delDiv = document.createElement('div');
    delDiv.setAttribute(
      'style',
      'display: inline-block;width: 30px; height: 32px; color: #FFF;cursor: pointer;float:right',
    );
    delDiv.id = 'cancelSpan';
    caozuoDiv.appendChild(delDiv);
    const delDivImg = document.createElement('img');
    delDivImg.src = `${closeImg}`;
    delDivImg.id = 'cancelSpan';
    delDiv.appendChild(delDivImg);
    const subDiv = document.createElement('div');
    subDiv.setAttribute(
      'style',
      'display: inline-block;width: 30px; height: 32px; color: #FFF;cursor: pointer;float:left',
    );
    subDiv.id = 'determineSpan';
    subDiv.innerHTML = '√';
    caozuoDiv.appendChild(subDiv);
    // 操作部分 top 结束----------------------------------------
    // x, √  操作部分 bottom------------------
    const caozuoDivT = document.createElement('div');
    caozuoDivT.setAttribute(
      'style',
      'text-align: center;position: absolute; bottom: -38px;right: 0px; background: #FC8B09; line-height: 32px;',
    );
    const delDivT = document.createElement('div');
    delDivT.setAttribute(
      'style',
      'display: inline-block;width: 30px; height: 32px; color: #FFF;cursor: pointer;float:right',
    );
    delDivT.id = 'cancelSpan';
    caozuoDivT.appendChild(delDivT);
    const delDivImgT = document.createElement('img');
    delDivImgT.src = `${closeImg}`;
    delDivImgT.id = 'cancelSpan';
    delDivT.appendChild(delDivImgT);
    const subDivT = document.createElement('div');
    subDivT.setAttribute(
      'style',
      'display: inline-block;width: 30px; height: 32px; color: #FFF;cursor: pointer;float:left',
    );
    subDivT.id = 'determineSpan';
    subDivT.innerHTML = '√';
    caozuoDivT.appendChild(subDivT);
    // 操作部分结束bottom----------------------------------------
    /*
    中间变量
    */
    let startXNew = 0;
    let startYNew = 0;
    let width;
    let height;
    const { clientHeight } = document.body;
    const tuozhuaiCoor = (e) => {
      // 阻止冒泡
      e.cancelBubble = true;
      // 父div
      const w = boxDiv.offsetWidth;
      const h = boxDiv.offsetHeight;
      const onMove = (event) => {
        const dpageX = e.pageX || e.targetTouches[0].pageX;
        const dpageY = e.pageY || e.targetTouches[0].pageY;
        const mpageX = event.pageX || event.targetTouches[0].pageX;
        const mpageY = event.pageY || event.targetTouches[0].pageY;
        if (e.target.id === 'sf') {
          // 右下角
          width = mpageX - dpageX + w > 65 ? mpageX - dpageX + w : 65;
          height = mpageY - dpageY + h > 65 ? mpageY - dpageY + h : 65;
        } else if (e.target.id === 'sfA') {
          // 左下角
          width = dpageX - mpageX + w > 65 ? dpageX - mpageX + w : 65;
          height = mpageY - dpageY + h > 65 ? mpageY - dpageY + h : 65;
          startXNew = event.pageX > e.pageX + w - 65 ? e.pageX + w - 65 : event.pageX;
          boxDiv.style.left = `${mpageX > dpageX + w - 65 ? dpageX + w - 65 : mpageX}px`;
        } else if (e.target.id === 'sfB') {
          // 右上角
          // 计算拉伸时镜框的宽高,左上角拉伸
          width = mpageX - dpageX + w > 65 ? mpageX - dpageX + w : 65;
          height = dpageY - mpageY + h > 65 ? dpageY - mpageY + h : 65;
          startYNew = mpageY > dpageY + h - 65 ? dpageY + h - 65 : mpageY;
          boxDiv.style.top = `${mpageY > dpageY + h - 65 ? dpageY + h - 65 : mpageY}px`;
        } else if (e.target.id === 'sfC') {
          // 左上角
          // 计算拉伸时镜框的宽高,右上角拉伸
          width = dpageX - mpageX + w > 65 ? dpageX - mpageX + w : 65;
          height = dpageY - mpageY + h > 65 ? dpageY - mpageY + h : 65;
          startXNew = mpageX > dpageX + w - 65 ? dpageX + w - 65 : mpageX;
          startYNew = mpageY > dpageY + h - 65 ? dpageY + h - 65 : mpageY;
          boxDiv.style.left = `${mpageX > dpageX + w - 65 ? dpageX + w - 65 : mpageX}px`;
          boxDiv.style.top = `${mpageY > dpageY + h - 65 ? dpageY + h - 65 : mpageY}px`;
        }
        boxDiv.style.background = `url(${ctxData}) no-repeat ${-startXNew - 3}px ${-startYNew - 3}px`;
        boxDiv.style.width = `${width}px`;
        boxDiv.style.height = `${height}px`;
        // 判断操作显示上边还是下边
        if (startYNew + height + 50 > clientHeight) {
          caozuoDivT.style.display = 'none';
          caozuoDiv.style.display = 'block';
        } else {
          caozuoDiv.style.display = 'none';
          caozuoDivT.style.display = 'block';
        }
      };
      const onUp = () => {
        boxDivBig.removeEventListener('mousemove', onMove);
        boxDivBig.removeEventListener('mouseup', onUp);
        boxDivBig.removeEventListener('touchmove', onMove);
        boxDivBig.removeEventListener('touchend', onUp);
        boxDiv.removeEventListener('mousemove', onMove);
        boxDiv.removeEventListener('mouseup', onUp);
        boxDiv.removeEventListener('touchmove', onMove);
        boxDiv.removeEventListener('touchend', onUp);
      };
      boxDivBig.addEventListener('mousemove', onMove);
      boxDivBig.addEventListener('mouseup', onUp);
      boxDivBig.addEventListener('touchmove', onMove);
      boxDivBig.addEventListener('touchend', onUp);
      boxDiv.addEventListener('mousemove', onMove);
      boxDiv.addEventListener('mouseup', onUp);
      boxDiv.addEventListener('touchmove', onMove);
      boxDiv.addEventListener('touchend', onUp);
    };
    const startDrag = (e) => {
      if (
        e.target.id === 'determineSpan' ||
        e.target.id === 'cancelSpan' ||
        e.target.id === 'determineSpan-id' ||
        e.target.id === 'cancelSpan-id' ||
        e.target.id === 'aa'
      ) {
        return resolve();
      }
      if (e.target.id === 'canvasBox') {
        return resolve();
      }
      // 如果存在则不重新画(点击空白处时，已有的不消失)
      if (document.getElementById('canvasBox')) {
        return resolve();
      }
      ele.style.cursor = '';
      const { clientX: startX, clientY: startY } = e;
      startXNew = startX || e.targetTouches[0].pageX;
      startYNew = startY || e.targetTouches[0].pageY;
      let moveH = 0;
      let deltaY1 = 0;
      let tuodong = false;
      // 保存截图
      const startDrag1 = (e) => {
        // const { clientX: startX1, clientY: startY1 } = e;
        const startX1 = e.clientX || e.targetTouches[0].pageX;
        const startY1 = e.clientY || e.targetTouches[0].pageY;
        const _isMouseDown = true;
        tuodong = false;
        // 判断确定和取消按钮不可移动
        if (e.target.id === 'determineSpan' || e.target.id === 'cancelSpan') {
          return;
        }
        const onMove1 = (e) => {
          if (tuodong) return;
          // canvas.off('mouse:up', vm.mouseUp);
          if (!_isMouseDown) return;
          e.stopImmediatePropagation();
          // const { clientX, clientY } = e;
          const clientX = e.clientX || e.targetTouches[0].pageX;
          const clientY = e.clientY || e.targetTouches[0].pageY;
          moveH = clientY;
          const deltaX1 = clientX - startX1;
          deltaY1 = clientY - startY1;
          // 移动距离加上原始距离
          const left = startXNew + deltaX1;
          const top = startYNew + deltaY1;
          boxDiv.style.left = `${left}px`;
          boxDiv.style.top = `${top}px`;
          boxDiv.style.backgroundPosition = `${-(left + 1)}px ${-(top + 1)}px`;
          boxDiv.style.background = `url(${ctxData}) no-repeat ${-left - 3}px ${-top - 3}px`;

          //------------------------------------------------------
          // 判断操作显示上边还是下边
          if (top + height + 50 > clientHeight) {
            caozuoDivT.style.display = 'none';
            caozuoDiv.style.display = 'block';
          } else {
            caozuoDiv.style.display = 'none';
            caozuoDivT.style.display = 'block';
          }
          boxDiv.appendChild(caozuoDiv);
          boxDiv.appendChild(caozuoDivT);

          if (width < 65 && height < 65) {
            ele.removeEventListener('mousedown', startDrag);
            ele.removeEventListener('touchstart', startDrag);
            ele.removeChild(boxDiv);
            ele.removeChild(boxDivBig);
            ele.removeChild(bgIimg);
            ele.style.cursor = '';
            resolve();
          }
          // const cancelSpanid = document.getElementById('cancelSpan-id');
          // const determineSpanid = document.getElementById('determineSpan-id');

          // if (!a) {
          delDiv.onclick = () => {
            ele.removeEventListener('mousedown', startDrag);
            ele.removeEventListener('touchstart', startDrag);
            ele.removeChild(boxDiv);
            ele.removeChild(boxDivBig);
            ele.removeChild(bgIimg);
            // boxDivBig.style.display = 'none';
            ele.style.cursor = '';
            // document.body.removeChild(ele);
            // 点击x
            // alert('x');
            callback && callback();
          };
          subDiv.onclick = () => {
            ele.removeEventListener('mousedown', startDrag);
            ele.removeEventListener('touchstart', startDrag);
            ele.removeChild(boxDiv);
            ele.removeChild(boxDivBig);
            ele.removeChild(bgIimg);
            // boxDivBig.style.display = 'none';
            ele.style.cursor = '';
            getBase64Image(ctxData, startXNew, startYNew, width, height).then(resolve);
            // 点击√
            // alert('√');
            callback && callback();
          };
          delDivT.onclick = () => {
            ele.removeEventListener('mousedown', startDrag);
            ele.removeEventListener('touchstart', startDrag);
            ele.removeChild(boxDiv);
            ele.removeChild(boxDivBig);
            ele.removeChild(bgIimg);
            // boxDivBig.style.display = 'none';
            ele.style.cursor = '';
            // document.body.removeChild(ele);
          };
          subDivT.onclick = () => {
            ele.removeEventListener('mousedown', startDrag);
            ele.removeEventListener('touchstart', startDrag);
            ele.removeChild(boxDiv);
            ele.removeChild(boxDivBig);
            ele.removeChild(bgIimg);
            // boxDivBig.style.display = 'none';
            ele.style.cursor = '';
            getBase64Image(ctxData, startXNew, startYNew, width, height).then(resolve);
          };
        };
        const onUp1 = () => {
          boxDiv.removeEventListener('mousemove', onMove1);
          boxDiv.removeEventListener('mouseup', onUp1);
          // 触摸处理: touchstart,touchmove,touchend
          boxDiv.removeEventListener('touchmove', onMove1);
          boxDiv.removeEventListener('touchend', onUp1);
          const left = boxDiv.style.left.slice(0, -2);
          const top = boxDiv.style.top.slice(0, -2);
          boxDiv.style.border = '2px solid #FC8B09';
          startXNew = Number(left);
          startYNew = Number(top);
          if (!_isMouseDown) {
            return false;
          }
        };

        boxDiv.addEventListener('mousemove', onMove1);
        boxDiv.addEventListener('mouseup', onUp1);
        // 触摸处理: touchstart,touchmove,touchend
        boxDiv.addEventListener('touchmove', onMove1);
        boxDiv.addEventListener('touchend', onUp1);
      };

      // const { clientX: startX, clientY: startY } = e;
      boxDiv.innerHTML = '';
      boxDiv.style.position = 'absolute';
      boxDiv.style.border = '0.5px solid #ccc';
      boxDiv.style.width = '0';
      boxDiv.style.height = '0';
      boxDiv.style.left = `${startXNew}px`;
      boxDiv.style.top = `${startYNew}px`;
      boxDiv.style.zIndex = 9999;
      boxDiv.id = 'canvasBox';
      // boxDivBig.style.cursor = 'pointer';
      ele.appendChild(boxDiv);
      const _isMouseDown = true;
      const onMove = (e) => {
        if (!_isMouseDown) return;
        e.stopImmediatePropagation();
        // const { pageX, pageY } = e;
        const pageX = e.pageX || e.targetTouches[0].pageX;
        const pageY = e.pageY || e.targetTouches[0].pageY;
        moveH = pageY;
        width = pageX - startXNew;
        height = pageY - startYNew;
        boxDiv.style.background = `url(${ctxData}) no-repeat ${-startXNew - 2}px ${-startYNew - 2}px`;
        boxDiv.style.width = `${width}px`;
        boxDiv.style.height = `${height}px`;
      };

      const onUp = () => {
        boxDiv.style.background = `url(${ctxData}) no-repeat ${-startXNew - 3}px ${-startYNew - 3}px`;
        // const { clientY } = e;
        ele.removeEventListener('mousemove', onMove);
        ele.removeEventListener('mouseup', onUp);

        boxDiv.addEventListener('mousedown', startDrag1);
        boxDiv.addEventListener('touchstart', startDrag1);
        // 触摸处理: touchstart,touchmove,touchend
        ele.removeEventListener('touchmove', onMove);
        ele.removeEventListener('touchend', onUp);

        // 判断操作显示上边还是下边
        if (moveH + 50 > clientHeight) {
          caozuoDivT.style.display = 'none';
          caozuoDiv.style.display = 'block';
        } else {
          caozuoDiv.style.display = 'none';
          caozuoDivT.style.display = 'block';
        }
        boxDiv.appendChild(caozuoDiv);
        boxDiv.appendChild(caozuoDivT);
        const suofang = document.createElement('div');
        suofang.setAttribute(
          'style',
          'z-index: 1990;position: absolute; display: block;cursor: se-resize;border-width: 8px 0px 0px 8px;border-style: solid;border-color: #FC8B09 transparent transparent;transform: rotateZ(90deg);right: 0;bottom: 0;',
        );
        suofang.id = 'sf';
        boxDiv.appendChild(suofang);
        // c
        const suofangA = document.createElement('div');
        suofangA.setAttribute(
          'style',
          'z-index: 1990; position: absolute;display: block;cursor: sw-resize;border-width: 8px 0px 0px 8px;border-style: solid; border-color: #FC8B09 transparent transparent;transform: rotateZ(-180deg);left: 0; bottom: 0;',
        );
        suofangA.id = 'sfA';
        boxDiv.appendChild(suofangA);
        // d
        const suofangB = document.createElement('div');
        suofangB.setAttribute(
          'style',
          'z-index: 1990; position: absolute;display: block;cursor: sw-resize;border-width: 8px 0px 0px 8px;border-style: solid; border-color: #FC8B09 transparent transparent;transform: rotateZ(0deg);right: 0;top: 0;',
        );
        suofangB.id = 'sfB';
        boxDiv.appendChild(suofangB);
        // e
        const suofangC = document.createElement('div');
        suofangC.setAttribute(
          'style',
          'z-index: 1990; position: absolute;display: block;cursor: se-resize; border-width: 8px 0px 0px 8px;border-style: solid;border-color: #FC8B09 transparent transparent;transform: rotateZ(-90deg);left: 0;top: 0;',
        );
        suofangC.id = 'sfC';
        boxDiv.appendChild(suofangC);
        boxDiv.style.border = '2px solid #FC8B09';
        if (width < 65 && height < 65) {
          ele.removeEventListener('mousedown', startDrag);
          ele.removeEventListener('touchstart', startDrag);
          ele.removeChild(boxDiv);
          ele.removeChild(boxDivBig);
          ele.removeChild(bgIimg);
          ele.style.cursor = '';
          resolve();
        }

        delDiv.onclick = () => {
          ele.removeEventListener('mousedown', startDrag);
          ele.removeEventListener('touchstart', startDrag);
          ele.removeChild(boxDiv);
          ele.removeChild(boxDivBig);
          ele.removeChild(bgIimg);
          ele.style.cursor = '';
          // alert('x');
          callback && callback();
        };
        // 触摸处理: touchstart,touchmove,touchend
        subDiv.onclick = () => {
          ele.removeEventListener('mousedown', startDrag);
          ele.removeEventListener('touchstart', startDrag);
          ele.removeChild(boxDiv);
          ele.removeChild(boxDivBig);
          ele.removeChild(bgIimg);
          ele.style.cursor = '';
          getBase64Image(ctxData, startXNew, startYNew, width, height).then(resolve);
          // alert('√');
          callback && callback();
        };
        delDivT.onclick = () => {
          ele.removeEventListener('mousedown', startDrag);
          ele.removeEventListener('touchstart', startDrag);
          ele.removeChild(boxDiv);
          ele.removeChild(boxDivBig);
          ele.removeChild(bgIimg);
          ele.style.cursor = '';
          callback && callback();
        };
        // 触摸处理: touchstart,touchmove,touchend
        subDivT.onclick = () => {
          ele.removeEventListener('mousedown', startDrag);
          ele.removeEventListener('touchstart', startDrag);
          ele.removeChild(boxDiv);
          ele.removeChild(boxDivBig);
          ele.style.cursor = '';
          callback && callback();
          getBase64Image(ctxData, startXNew, startYNew, width, height).then(resolve);
        };
        suofang.addEventListener('mousedown', tuozhuaiCoor);
        suofang.addEventListener('touchstart', tuozhuaiCoor);

        suofangA.addEventListener('mousedown', tuozhuaiCoor);
        suofangA.addEventListener('touchstart', tuozhuaiCoor);

        suofangB.addEventListener('mousedown', tuozhuaiCoor);
        suofangB.addEventListener('touchstart', tuozhuaiCoor);

        suofangC.addEventListener('mousedown', tuozhuaiCoor);
        suofangC.addEventListener('touchstart', tuozhuaiCoor);

        document.onmouseup = () => {
          tuodong = false;
          if (width < 65 && height < 65) {
            ele.removeEventListener('mousedown', startDrag);
            ele.removeEventListener('touchstart', startDrag);
            ele.removeChild(boxDiv);
            ele.removeChild(boxDivBig);
            ele.removeChild(bgIimg);
            ele.style.cursor = '';
            resolve();
          }
          ele.removeEventListener('mousemove', onMove);
          ele.removeEventListener('touchmove', onMove);
        };
        document.addEventListener('touchend', () => {
          tuodong = false;
          if (width < 65 && height < 65) {
            ele.removeEventListener('mousedown', startDrag);
            ele.removeEventListener('touchstart', startDrag);
            ele.removeChild(boxDiv);
            ele.removeChild(boxDivBig);
            ele.removeChild(bgIimg);
            ele.style.cursor = '';
            resolve();
          }
          ele.removeEventListener('mousemove', onMove);
          ele.removeEventListener('touchmove', onMove);
        });
        // }

        // a = true;
        if (!_isMouseDown) {
          return false;
        }
      };

      ele.addEventListener('mousemove', onMove);
      ele.addEventListener('mouseup', onUp);
      // 触摸处理: touchstart,touchmove,touchend
      ele.addEventListener('touchmove', onMove);
      ele.addEventListener('touchend', onUp);
    };
    const keyup = (e) => {
      e.preventDefault();
      if (e.keyCode === 27) {
        resolve();
        const m = ele.querySelector('.boxDivBig');
        if (!m) return;
        ele.removeChild(boxDiv);
        ele.removeChild(boxDivBig);
        ele.removeChild(bgIimg);
        ele.style.cursor = '';
        ele.removeEventListener('mousedown', startDrag);
        ele.removeEventListener('touchend', startDrag);
      }
    };
    document.onkeydown = keyup;
    ele.addEventListener('mousedown', startDrag);
    ele.addEventListener('touchstart', startDrag);
  });

function setStyles(element, styles) {
  for (let property in styles) {
    if (styles.hasOwnProperty(property)) {
      element.style[property] = styles[property];
    }
  }
}
